<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>删除子字符串的最大得分</title>
</head>

<body>
  <script>

    // 贪心
    var maximumGain = function (s, x, y) {
      let a, b
      // 保持最大的值为x，并帮定相应字符
      if (x >= y) {
        a = 'a'
        b = 'b'
      } else {
        let t = y
        y = x
        x = t
        a = 'b'
        b = 'a'
      }
      s += 'l'  // 最后加一个隔断字符，防止以ab结尾的字符串没有结算
      let j = 0, k = 0, rst = 0 // j, k记录a 和 b个数
      for (let i = 0; i < s.length; i++) {
        if (s[i] == a) {
          j++
        }
        else if (s[i] == b) {
          if (j !== 0) {
            // 结算ab
            rst += x
            j--
          } else {
            k++
          }
        } else {
          rst += Math.min(j, k) * y
          j = 0
          k = 0
        }
      }
      return rst
    };
  </script>
</body>

</html>